from rest_framework.views import exception_handler as drf_exception_handler
from rest_framework.views import Response

from utils.get_request_info import get_request_canonical_path, get_request_ip, get_browser, get_login_location, get_os
from monitar.models import ErrorLog, ErrorDetail
from utils.loggin import logger

def exception_handler(exc, context):
    response = drf_exception_handler(exc, context)
    request = context.get('request')
    if response is None:  # drf没有处理的，django的异常
        response = Response({'code': 999, 'msg': '服务器异常，请重试...'})
    else:
        try:
            msg = response.data['detail']
        except Exception:
            msg = '未知异常'
        response = Response({'code': 998, 'msg': msg})
    if request.data:
        body = request.data
    elif request.GET:
        body = request.GET
    else:
        body = request.META
    data = {
        'request_path': get_request_canonical_path(request),
        'request_body': body,
        'request_method': request.method,
        'request_ip': get_request_ip(request),
        'request_browser': get_browser(request),
        'request_location': get_login_location(request),
        'request_os': get_os(request),
        'creator': request.user if request.user else 'AnonymousUser',
    }
    try:
        errorDetail = ErrorDetail.objects.create(detail=exc)
        data['detail'] = errorDetail
        ErrorLog.objects.create(**data)
    except Exception:
        pass
    logger.critical('%s' % exc)
    return response